package com.zzz.order.service;

import com.zzz.order.mapper.OrderMapper;
import com.zzz.order.model.OrderInfo;
import com.zzz.order.model.ProductInfo;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/*
 * @author zzr
 * @date: 2025/10/15  17:03
 * @description:
 */

@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Resource
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    private static AtomicInteger count = new AtomicInteger(1);

    private static List<ServiceInstance> instances;

    @PostConstruct
    public void init() {
        // 根据应用名称获取服务列表
        instances = discoveryClient.getInstances("product-service");
    }

    //    public OrderInfo selectOrderById(Integer orderId) {
//
//        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
////        String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();
//
//        // 服务可能有多个，轮询获取实例
//        int index =  count.getAndIncrement() % instances.size();
//
//        ServiceInstance instance = instances.get(index);
//
//        log.info(instance.getInstanceId());
//
//        String url = instance.getUri() + "/product/" + orderInfo.getProductId();
//
//        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
//        orderInfo.setProductInfo(productInfo);
//        return orderInfo;
//    }
    public OrderInfo selectOrderById(Integer orderId) {

        OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
//        String url = "http://127.0.0.1:9090/product/" + orderInfo.getProductId();

        String url = "http://product-service/product/" + orderInfo.getProductId();
        ProductInfo productInfo = restTemplate.getForObject(url, ProductInfo.class);
        orderInfo.setProductInfo(productInfo);
        return orderInfo;
    }
}
